/**
 * 
 */
package com.effectiv.req1.controller;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.effectiv.req1.domain.Project;

import com.effectiv.req1.domain.User;
import com.effectiv.req1.repository.LovRepository;
import com.effectiv.req1.repository.ProjectRepository;
import com.effectiv.req1.repository.UserRepository;

/**
 * @author Dhrubo
 * 
 */
@Controller
@Slf4j
public class ProjectUserController {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private ProjectRepository projectRepository;
	@Autowired
	private LovRepository lovRepository;

	@RequestMapping(value = "/newprojectuser")
	public final String addprojectuser(@RequestParam("user") String userId,
			@RequestParam("project") String projectId, Model model) {

		model.addAttribute(userRepository.findOne(userId));
		model.addAttribute(projectRepository.findOne(projectId));

		return "newprojectuser";
	}

	@RequestMapping(value = "/saveprojectuser")
	public final String saveProjectUser(@RequestParam("user") String userId,
			@RequestParam("project") String projectId, Model model) {

		User user = userRepository.findOne(userId);
		Project project = projectRepository.findOne(projectId);

		List<User> users = project.getUsers();

		if (users == null) {
			users = new ArrayList<User>();
		}

		if (!users.contains(user)) {
			users.add(user);

			project.setUsers(users);

			
			projectRepository.save(project);
		}
		model.addAttribute(user);
		model.addAttribute(project);


		return "newprojectuser";
	}

}
